package com.ijiuchuang.jc_localization.view.fragment;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ijiuchuang.jc_localization.R;
import com.ijiuchuang.jc_localization.base.BaseFragment;
import com.ijiuchuang.jc_localization.bean.lite.Map;
import com.ijiuchuang.jc_localization.bean.lite.Station;
import com.ijiuchuang.jc_localization.contract.settings.SettsMapDetailContract;
import com.ijiuchuang.jc_localization.presenter.settings.SettsMapDetailPresenter;
import com.ijiuchuang.jc_localization.tools.utils.Log;
import com.ijiuchuang.jc_localization.tools.views.MapView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;

/**
 * A simple {@link Fragment} subclass.
 */
public class SettsMapDetailFragment extends BaseFragment implements SettsMapDetailContract.View {

    public static final String BUNDLE_MAP = "SettsMapDetailFragment.BUNDLE_MAP";

    @BindView(R.id.setts_map_detail_image)
    MapView mapView;
    @BindView(R.id.setts_map_detail_spinner)
    AppCompatSpinner mapSpinner;
    @BindView(R.id.setts_map_detail_edit_name)
    AutoCompleteTextView editName;
    @BindView(R.id.map_detail_fab)
    FloatingActionButton fab;
    @BindView(R.id.map_detail_frame)
    LinearLayout frameView;
    @BindView(R.id.setts_map_detail_switch)
    SwitchCompat defaultSwitch;
    @BindView(R.id.setts_map_detail_linear_default)
    LinearLayout linearDefault;
    @BindView(R.id.setts_map_detail_text_size)
    TextView textSize;
    @BindView(R.id.setts_map_detail_scroll)
    ScrollView scrollView;
    @BindView(R.id.setts_map_detail_linear_map)
    LinearLayout linearMap;
    @BindView(R.id.setts_map_detail_linear_station)
    LinearLayout linearStation;
    @BindView(R.id.setts_map_detail_scroll_text_name)
    TextInputLayout textName;
    @BindView(R.id.setts_map_detail_button_fullscreen)
    AppCompatButton buttonFullscreen;
    @BindView(R.id.setts_map_detail_button_save)
    AppCompatButton buttonSave;
    @BindView(R.id.setts_map_detail_button_add)
    AppCompatButton buttonAdd;
    @BindView(R.id.setts_map_detail_scroll_linear_top)
    LinearLayout linearTop;
    @BindView(R.id.setts_map_detail_spinner_station)
    AppCompatSpinner spinnerStation;

    private SettsMapDetailContract.Presenter presenter;

    public SettsMapDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_setts_map_detail, container, false);
        ButterKnife.bind(this, view);

        presenter = new SettsMapDetailPresenter(getActivity(), this);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        presenter.start();

        presenter.loadConfig(getMap());
    }

    @OnItemSelected(R.id.setts_map_detail_spinner)
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        presenter.getMapBitmap(position);
    }

    @Override
    public void setDatas(String[] datas) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, datas);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mapSpinner.setAdapter(adapter);
    }

    @Override
    public void setMap(Bitmap bitmap) {
        mapView.setImageBitmap(bitmap);
    }

    @Override
    public void setSpinner(int position) {
        mapSpinner.setSelection(position);
    }

    @Override
    public String getName() {
        return editName.getText().toString().trim();
    }

    @Override
    public int getSpinner() {
        return mapSpinner.getSelectedItemPosition();
    }

    @Override
    public Map getMap() {
        Bundle bundle = getActivity().getIntent().getExtras();
        Map map = (Map) bundle.getSerializable(BUNDLE_MAP);
        return map;
    }

    @Override
    public void addStations(Station... stations) {
        mapView.clearPointTest();
        mapView.setStations(stations);
    }

    @Override
    public void setStationSpinner(List<String> stations) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, stations);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerStation.setAdapter(adapter);
        spinnerStation.setSelection(0, false);
        spinnerStation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                presenter.getSelectStation(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // PINK:  添加动作
    }

    @Override
    public void setName(@NonNull String name) {
        editName.setHint(name);
    }

    @Override
    public void setSubtitle(String title) {
        getActionBar().setSubtitle(title);
    }

    @Override
    public void setSwitchChecked(boolean isChecked) {
        defaultSwitch.setChecked(isChecked);
    }

    @Override
    public void setDefaultLinearVisibility(boolean isVisiable) {
        if (isVisiable) {
            linearDefault.setVisibility(View.VISIBLE);
        } else {
            linearDefault.setVisibility(View.GONE);
        }
    }

    @Override
    public void setSize(String size) {
        textSize.setText(size);
    }

    @Override
    public void showUpdateStation(final Station station) {
        View view = View.inflate(getActivity(), R.layout.dialog_add_station, null);
        final ViewHolder holder = new ViewHolder(view);
        holder.editX.setText(""+station.getX());
        holder.editY.setText(""+station.getY());
        holder.editNum.setText(""+station.getNum());
        holder.editMac.setText(station.getMac());
        holder.editLimit.setText(""+station.getLimit());
        holder.editRemark.setText(station.getRemark());

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.dialog_title_info)
                .setPositiveButton(R.string.dialog_btn_submit, null)
                .setNegativeButton(R.string.dialog_btn_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setView(view)
                .create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (presenter.updateVerify(station,
                        holder.editNum.getText().toString().trim(),
                        holder.editMac.getText().toString().trim(),
                        holder.editX.getText().toString().trim(),
                        holder.editY.getText().toString().trim(),
                        holder.editLimit.getText().toString().trim(),
                        holder.editRemark.getText().toString().trim(),
                        holder.switchShown.isChecked(),
                        getMap())) {
                    dialog.dismiss();
                }
            }
        });
    }

    @Override
    public void animationFull() {
        ObjectAnimator anim = ObjectAnimator
                .ofFloat(mapView, "veev", 0.0F, 1.0F)
                .setDuration(2000);
        anim.start();

        final ViewGroup.LayoutParams paramsMap = mapView.getLayoutParams();
        final ViewGroup.LayoutParams paramsSave = buttonSave.getLayoutParams();
        final ViewGroup.LayoutParams paramsTop = linearTop.getLayoutParams();

        final int height = mapView.getMeasuredHeight();
        final int width = mapView.getMeasuredWidth();
        final int widthSave = (int) getResources().getDimension(R.dimen.setts_map_detail_button_SIZE);

        final int defaultHeight = linearTop.getMeasuredHeight();
        presenter.setTopHeight(defaultHeight);

        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                paramsMap.height = (int) (height + ((width - height) * cVal));
                paramsSave.width = (int) (widthSave - widthSave * cVal);
                paramsTop.height = (int) (defaultHeight * (1 - cVal));

                mapView.setLayoutParams(paramsMap);
                buttonSave.setLayoutParams(paramsSave);
                linearTop.setLayoutParams(paramsTop);
            }
        });

        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0.5f);

        AnimatorSet setGo = new AnimatorSet();
        setGo.playTogether(
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleX", 1.0f, 0.5f),
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleY", 1.0f, 0.5f),
                ObjectAnimator.ofFloat(buttonFullscreen, "alpha", 1.0f, 0.5f)
        );
        setGo.setDuration(1000).start();

        final AnimatorSet setBack = new AnimatorSet();
        setBack.playTogether(
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleX", 0.5f, 1.0f),
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleY", 0.5f, 1.0f),
                ObjectAnimator.ofFloat(buttonFullscreen, "alpha", 0.5f, 1f)
        );
        setBack.setDuration(1000);

        setGo.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                buttonFullscreen.setBackgroundResource(R.drawable.sel_button_fullscreen_exit);
                setBack.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

    }

    @Override
    public void animationFullExit() {
        ObjectAnimator anim = ObjectAnimator
                .ofFloat(mapView, "veev", 1.0F, 0.0F)
                .setDuration(2000);
        anim.start();

        final ViewGroup.LayoutParams paramsMapImage = mapView.getLayoutParams();
        final ViewGroup.LayoutParams paramsSave = buttonSave.getLayoutParams();
        final ViewGroup.LayoutParams paramsTop = linearTop.getLayoutParams();

        final int mapImageOriginHeight = (int) getResources().getDimension(R.dimen.setts_map_detail_image_HEIGHT);
        final int mapImageHeight = paramsMapImage.height;
        final int widthSave = (int) getResources().getDimension(R.dimen.setts_map_detail_button_SIZE);

        final int defaultHeight = presenter.getTopHeight();

        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                paramsMapImage.height = (int) (mapImageOriginHeight + (mapImageHeight - mapImageOriginHeight) * cVal);
                paramsSave.width = (int) (widthSave - widthSave * cVal);
                paramsTop.height = (int) (defaultHeight * (1 - cVal));

                mapView.setLayoutParams(paramsMapImage);
                buttonSave.setLayoutParams(paramsSave);
                linearTop.setLayoutParams(paramsTop);
            }
        });

        AnimatorSet setGo = new AnimatorSet();
        setGo.playTogether(
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleX", 1.0f, 1.5f),
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleY", 1.0f, 1.5f),
                ObjectAnimator.ofFloat(buttonFullscreen, "alpha", 1.0f, 0.5f)
        );
        setGo.setDuration(1000).start();

        final AnimatorSet setBack = new AnimatorSet();
        setBack.playTogether(
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleX", 1.5f, 1.0f),
                ObjectAnimator.ofFloat(buttonFullscreen, "scaleY", 1.5f, 1.0f),
                ObjectAnimator.ofFloat(buttonFullscreen, "alpha", 0.5f, 1f)
        );
        setBack.setDuration(1000);

        setGo.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                buttonFullscreen.setBackgroundResource(R.drawable.sel_button_fullscreen);
                setBack.start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    @Override
    public void setPresenter(SettsMapDetailContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @OnClick(R.id.map_detail_fab)
    public void onClick() {
        Snackbar.make(frameView, R.string.snack_title_save, Snackbar.LENGTH_SHORT)
                .setCallback(new Snackbar.Callback() {
                    @Override
                    public void onDismissed(Snackbar snackbar, int event) {
                        fab.show();
                    }

                    @Override
                    public void onShown(Snackbar snackbar) {
                        fab.hide();
                    }
                })
                .setAction(R.string.snack_action_ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        presenter.saveMap(getMap(), getName(), getSpinner());
                    }
                })
                .show();
    }

    @OnClick(R.id.setts_map_detail_switch)
    public void onCheckChanged() {
        if (defaultSwitch.isChecked()) {
            presenter.setDefault(getMap());
        }
    }

    @OnClick({
            R.id.map_detail_fab,
            R.id.setts_map_detail_button_fullscreen,
            R.id.setts_map_detail_button_save,
            R.id.setts_map_detail_button_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.setts_map_detail_button_fullscreen:
                presenter.getAnimation();
                break;
            case R.id.setts_map_detail_button_save:
                Snackbar.make(frameView, R.string.snack_title_save, Snackbar.LENGTH_SHORT)
                        .setAction(R.string.snack_action_ok, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                presenter.saveMap(getMap(), getName(), getSpinner());
                            }
                        })
                        .show();
                break;
            case R.id.map_detail_fab:
                break;
            case R.id.setts_map_detail_button_add:
                if (mapView.getPointTest() != null) {
                    Log.i("Point: " + mapView.getPointTest().toString());
                    showAddStation(mapView.getPointTest());
                }
                break;
        }
    }

    private void showAddStation(@NonNull final Point point) {
        View view = View.inflate(getActivity(), R.layout.dialog_add_station, null);
        final ViewHolder holder = new ViewHolder(view);
        holder.editX.setText("" + point.x);
        holder.editY.setText("" + point.y);
        holder.editNum.setText("1");
        holder.editMac.setText("01");
        holder.editLimit.setText("90");
        holder.editRemark.setText("基站部署");

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.dialog_title_info)
                .setPositiveButton(R.string.dialog_btn_submit, null)
                .setNegativeButton(R.string.dialog_btn_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setView(view)
                .create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (presenter.inputVerify(holder.editNum.getText().toString().trim(),
                        holder.editMac.getText().toString().trim(),
                        holder.editX.getText().toString().trim(),
                        holder.editY.getText().toString().trim(),
                        holder.editLimit.getText().toString().trim(),
                        holder.editRemark.getText().toString().trim(),
                        holder.switchShown.isChecked(),
                        getMap())) {
                    dialog.dismiss();
                }
            }
        });
    }

    static class ViewHolder {
        @BindView(R.id.dialog_add_station_edit_num)
        AutoCompleteTextView editNum;
        @BindView(R.id.dialog_add_station_edit_mac)
        AutoCompleteTextView editMac;
        @BindView(R.id.dialog_add_station_edit_x)
        AutoCompleteTextView editX;
        @BindView(R.id.dialog_add_station_edit_y)
        AutoCompleteTextView editY;
        @BindView(R.id.dialog_add_station_edit_limit)
        AutoCompleteTextView editLimit;
        @BindView(R.id.dialog_add_station_edit_remark)
        AutoCompleteTextView editRemark;
        @BindView(R.id.dialog_add_station_switch_shown)
        SwitchCompat switchShown;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
